﻿(function() {
    var db = require("../../core/db/index");
    var config = require("../../core/_include/config");

    var BusCon = require("../../core/bus/_con");
    var UserCon = require("../../core/user/_con");
    var AdminCon = require("../../core/admin/_con");
    var $Object = require("../../core/_include/$.Object");
    var WX_V2 = require("../../my_modules/wx/wx.v2");
    var WX_V2_instance_cache = {};
    var md5 = require("../../core/_include/md5");



    var role = {
        checkCode: function(app, code_hash, code) {
            code || (code = app.request.query.code || app.request.body.code);

            if (!code || !code.trim()) {
                throwCusError("验证码不可为空")
            }
            var code_cookie = app.cookies.get(code_hash);

            var trueLoginCode = ccapCache[code_cookie];
            if (!trueLoginCode) {
                throwCusError("验证码超时");
            }
            if (code.toLowerCase() !== trueLoginCode) {
                throwCusError("验证码错误")
            }
        },
        getUser: function(app) {
            var loginerHash = app.cookies.get("loginSession");
            console.log("USER HASH:", loginerHash);
            var loginInfo = db.find_by_id(config.dbname.loginHash, loginerHash);
            if (loginInfo) {
                if ((loginInfo.time + config.autoSignUpTime) < +new Date) {
                    db.remove(config.dbname.loginHash, loginerHash);
                    throwCusError("用户登录超时，请重新登录");
                } else if (loginInfo.type !== "user") {
                    throwCusError("cookie值无效");
                } else {
                    loginInfo.time = +new Date;
                    db.update(config.dbname.loginHash, loginInfo._id, loginInfo);
                    var user = UserCon.get(loginInfo.user_id);
                    if (loginInfo.as_MA) {
                        user.MA = user.getMA();
                    }
                    return user
                }
            } else {
                throwCusError("您还未登录");
            }
        },
        // getSockUser: function(conn) {
        // 	var loginerHash = conn.loginSession;
        // 	var loginInfo = db.find_by_id(config.dbname.loginHash, loginerHash);
        // 	if (loginInfo) {
        // 		if ((loginInfo.time + config.autoSignUpTime) < +new Date) {
        // 			db.remove(config.dbname.loginHash, loginerHash);
        // 			throw "用户sock登录超时，请重新登录";
        // 		} else if (loginInfo.type !== "user") {
        // 			throw "cookie值无效";
        // 		} else {
        // 			loginInfo.time = +new Date;
        // 			db.update(config.dbname.loginHash, loginInfo._id, loginInfo);
        // 			return UserCon.get(loginInfo.user_id)
        // 		}
        // 	} else {
        // 		throw "客户端未登录";
        // 	}
        // },
        getUserSockSet: function(user_id) {
            var connsSet = notify.conns[user_id] || []
            return connsSet;
        },
        getAllUserSockSet: function() {
            var connsSet = [];
            for (var man_id in notify.conns) {
                var man_set = notify.conns[man_id];
                var man_con;
                if (man_set instanceof Array && (man_con = man_set[0])) {
                    if (man_con.s_info.type == "user") {
                        connsSet = connsSet.concat(man_set)
                    }
                }
            }
            return connsSet;
        },
        getBusSockSet: function(bus_id) {
            var connsSet = notify.conns[bus_id] || []
            return connsSet;
        },
        getBus: function(app) {
            var loginerHash = app.cookies.get("bus_loginSession");
            var bus_id = app.cookies.get("bus_login_id");
            if (!(loginerHash && bus_id)) {
                throwCusError("客户端未登录");
            }
            console.log("当前HASH所指定商家：", bus_id, loginerHash);
            var loginInfo = db.find_by_id(config.dbname.loginHash, bus_id);
            if (loginInfo) {
                for (var i = 0, item; item = loginInfo.loginers_arr[i]; i += 1) {
                    if (item.hash === loginerHash) {
                        if (!item.time || item.time < item.login_time) {
                            item.time = item.login_time
                        }
                        if ((item.time + config.autoSignUpTime) < +new Date) {
                            throwCusError("商家登录超时，请重新登录");
                        } else {
                            //刷新最后的登录时间
                            item.time = +new Date;
                            db.update(config.dbname.loginHash, loginInfo._id, loginInfo)
                            break;
                        }
                    }
                }
                if (i === loginInfo.loginers_arr.length) {
                    throwCusError("cookie值无效");
                } else {
                    var bus = BusCon.get(loginInfo._id);
                    //带上商家的地址
                    var bus_url = bus.getOneVisitableUrl();
                    bus.url = bus_url;
                    bus._current_employee = item.employees;

                    return bus;
                }
            } else {
                throwCusError("客户端未登录");
            }
        },
        getBusInfo: function(app) {
            var bus_id = app.request.headers["bus_id"];
            if (!bus_id) {
                throwCusError("所用域名无匹配商家，请联系官方人员进行确认");
            }
            var bus = BusCon.get(bus_id);
            return $Object.clone(bus);
        },
        get_WX_V2_instance: function(app, bus_id) {
            if (bus_id) {
                var bus = BusCon.get(bus_id);
                var bus_info = bus && bus.info;
            }
            bus_info || (bus_info = role.getBusInfo(app).info);

            console.log("BUS_ID:", bus_id || app.request.headers["bus_id"]);

            var wx_config = bus_info.wx_config || {};

            if (wx_config.appId && wx_config.appSecret && wx_config.mchId && wx_config.Key) {
                var _cache_key = wx_config.appId + "|" + wx_config.appSecret + "|" + wx_config.mchId + "|" + wx_config.Key;
                console.log("WX CONFIG INFO:", _cache_key);
                return WX_V2_instance_cache[_cache_key] || (WX_V2_instance_cache[_cache_key] = new WX_V2(wx_config.appId, wx_config.appSecret, wx_config.mchId, wx_config.Key))
            } else {
                console.log("WX CONFIG INFO:", "USE DOTNAR!");
                return WX_V2.dotnar_instance;
            }
        },
        //将商家设置为已登录状态
        loginBus: function(app, bus) {
            //注入新的Session
            var hash = app.cookies.get("bus_loginSession") || "loginHash_" + (+new Date).toString(16);
            //获取登录集合信息
            var loginer_info = db.find_by_id(config.dbname.loginHash, bus._id);
            if (loginer_info) {
                var loginer_item = {
                    hash: hash,
                    employees: bus._current_employee,
                    login_time: +new Date
                };
                var _index
                var is_no_logined = loginer_info.loginers_arr.every(function(item, i) {
                    _index = i;
                    return item.hash !== hash
                });
                if (is_no_logined) {
                    loginer_info.loginers_arr.push(loginer_item);
                } else {
                    loginer_info.loginers_arr.splice(_index, 1, loginer_item);
                }
            } else {
                loginer_info = {
                    _id: bus._id,
                    type: "bus",
                    loginers_arr: [{
                        hash: hash,
                        employees: bus._current_employee,
                        login_time: +new Date
                    }]
                }
            }
            db.update(config.dbname.loginHash, loginer_info._id, loginer_info);
            app.cookies.set("bus_loginSession", hash, {
                expires: new Date("2100-1-1")
            });
            app.cookies.set("bus_login_id", bus._id, {
                expires: new Date("2100-1-1")
            });
        },
        loginUser: function(app, user, options) {
            var userHash = app.cookies.get("loginSession");
            if (!userHash) {
                options || (options = {});
                //删除loginHash中同用户名的信息
                db.remove_list(config.dbname.loginHash, {
                    user_id: user._id
                });
                //注入新的Session
                console.log(userHash)
                var hash = md5.md5_2('USER:' + user._id.substr(2));
                app.cookies.set("loginSession", hash, {
                    expires: new Date((+new Date) + config.autoSignUpTime)
                });
            }

            var as_MA = !!options.as_MA //登录为市代
            db.insert(config.dbname.loginHash, {
                _id: hash,
                user_id: user._id,
                type: "user",
                beginTime: +new Date,
                as_MA: as_MA
            });
            if (as_MA) {
                user.getMA();
            }
        },
        getAdmin: function(app) {
            var loginerHash = app.cookies.get("admin_loginSession");
            var loginInfo = db.find_by_id(config.dbname.loginHash, loginerHash);
            if (loginInfo) {
                if ((loginInfo.time + config.autoSignUpTime) < +new Date) {
                    db.remove(config.dbname.loginHash, loginerHash);
                    throwCusError("管理员登录超时，请重新登录");
                } else if (loginInfo.type !== "admin") {
                    throwCusError("cookie值无效");
                } else {
                    loginInfo.time = +new Date;
                    db.update(config.dbname.loginHash, loginerHash, loginInfo);
                    return AdminCon.get(loginInfo.admin_id)
                }
            } else {
                throwCusError("管理员未登录");
            }
        },
        checkRole: function(type, app) {
            var loginerHash = app.cookies.get("loginSession");
            var loginInfo = db.find_by_id(config.dbname.loginHash, loginerHash);
            // console.log("loginInfo:", loginInfo);
            if (loginInfo) {
                switch (type) {
                    case "user":
                        return loginInfo.type === type || loginInfo.type === "admin";
                    case "bus":
                        return loginInfo.type === type || loginInfo.type === "admin";
                    default:
                        return loginInfo.type === "admin";
                }
            } else {
                throwCusError("客户端未登录");
            }
        },
        resCheckRole: function(type, app) {
            console.log("权限检查！", type);
            try {
                if (!type) {
                    throwCusError("参数错误");
                } else if (role.checkRole(type, app)) {
                    //拥有足够的权限，继续运行
                } else {
                    throwCusError("权限不足");
                }
                return true;
            } catch (e) {
                app.body = ResponObj("error", e);
                // throwCusError("用户权限检查结束，中断："+e);
                return false;
            }
        },
    };
    module.exports = role;
    var ResponObj = require("../_include/responObj");
    var notify = require("./notify");
}());
